package org.fordprefect.struts2lightboxplugin.util;

import javax.imageio.ImageIO;
import java.io.IOException;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.awt.image.BufferedImage;


/**
 * Created by IntelliJ IDEA.
 * User: milmber
 * Date: Aug 31, 2007
 * Time: 7:10:19 PM
 * To change this template use File | Settings | File Templates.
 */
public class ImageUtil {

    public static boolean scaleImage(String name, String format, InputStream in, OutputStream out, int width, int height)
			throws IOException {
		BufferedImage image = ImageIO.read(in);
		if (image == null)
			throw new IllegalArgumentException("Could not create image from InputStream argument.");
		// resize the image if either width or height is 0
		if (height == 0 && width != 0) {
			double w = image.getWidth() / width;
			height = (int) (image.getHeight() / w);
		} else if (width == 0 && height != 0) {
			double h = image.getHeight() / height;
			width = (int) (image.getWidth() / h);
		}
		image = getScaledImage(image, width, height);
		if (null == format)
			format = name.substring(name.lastIndexOf('.') + 1).toLowerCase();
		return ImageIO.write(image, format, out);
	}

	public static boolean scaleImage(File input, File output, double xscale, double yscale) throws IOException {
		BufferedImage image = ImageIO.read(input);
		if (image == null)
			throw new IllegalArgumentException("Could not create image from input File argument.");
		image = getScaledImage(image, xscale, yscale);
		String name = output.getName();
		String format = "png";
		if(name.lastIndexOf(".") != -1)
			format = name.substring(name.lastIndexOf('.') + 1).toLowerCase();
		return ImageIO.write(image, format, output);
	}

	static BufferedImage getScaledImage(BufferedImage source, int width, int height) {
		// assert(source != null && width > 0 && height > 0);
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		image.createGraphics().drawImage(source, 0, 0, width, height, null);
		return image;
	}

	static BufferedImage getScaledImage(BufferedImage source, double xscale, double yscale) {
		return getScaledImage(source, (int) (source.getWidth() * xscale), (int) (source.getHeight() * yscale));
	}

}
